package com.example.cslp.exception.handler;




import com.example.cslp.web.JsonResult;
import com.example.cslp.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * 统一处理异常
 * @author ming
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    public GlobalExceptionHandler() {
        log.debug("创建统一处理异常的对象：GlobalExceptionHandler");
    }

    @ExceptionHandler
    public JsonResult handleServiceException(ServiceException e) {
        log.error("统一处理ServiceException，将向客户端响应：{}", e.getMessage());
        return JsonResult.fail(e);
    }

    @ExceptionHandler
    public JsonResult handleValidationException(ValidatorException e){
        log.error("参数校验异常,将向客户端响应：{}",e.getMessage());
        return JsonResult.fail(ServiceCode.ERR_UNKNOWN,e.getMessage());
    }

    @ExceptionHandler
    public JsonResult handlenMissingServletRequerstPartExcetion(MissingServletRequestPartException e){
        log.debug("出现异常{}",e.getMessage());
        return JsonResult.fail(ServiceCode.ERR_UNKNOWN,e.getMessage());
    }

    @ExceptionHandler
    public JsonResult handlenHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e){
        log.debug("出现异常{}",e.getMessage());
        return JsonResult.fail(ServiceCode.ERR_UNKNOWN,e.getMessage());
    }


    @ExceptionHandler
    public JsonResult handleThrowable(Throwable e) {
        log.error("统一处理未明确处理的异常【{}】，将向客户端响应：{}", e.getClass().getName(), e.getMessage());
        e.printStackTrace();
        String message = "服务器忙，请联系管理员！";
        return JsonResult.fail(ServiceCode.ERR_UNKNOWN, message);
    }

}
